package com.example.libraryapp.fragment;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;

import com.example.libraryapp.R;
import com.example.libraryapp.book.BookInfo;
import com.example.libraryapp.lend.LendInfo;
import com.example.libraryapp.lend.LendService;
import com.example.libraryapp.util.Constance;

/**
 * 借阅Fragment
 */
public class SecondFragment extends Fragment implements OnQueryTextListener {
	
	private static Handler handler;
	private Context context;
	private SearchView svSearch;
	private ListView lvlend;
	private lendAdapter lendAdapter;
	private List<LendInfo> lendList;
	private TextView tvTotal;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		init();
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if (container == null) {
			return null;
		}
		View view = inflater.inflate(R.layout.second_fragment, container, false);
		findViews(view);
		return view;
	}
	
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getAllLendInfo();
	}

	/**
	 * 得到所有借阅信息
	 */
	private void getAllLendInfo() {
		//清理数据库
		//LendService.clear(context);
		lendList = LendService.getAllLend(context);
		lendAdapter.setData(lendList);
		lendAdapter.notifyDataSetChanged();
		if (lendList == null) {
			tvTotal.setText("共计 0  条数据");
		} else {
			tvTotal.setText("共计 " + lendList.size() + "  条数据");
		}
	}
	/**
	 * 根据条件查询借阅信息
	 * @param param
	 */
	private void getLendInfoByParam(String param) {
		lendList = LendService.getLendInfoByParam(context, param);
	}
	
	/**
	 * 找到控件
	 */
	private void findViews(View view) {
		svSearch = (SearchView) view.findViewById(R.id.search_view);
		svSearch.setSubmitButtonEnabled(true);
		svSearch.setFocusable(false);
		// 为改SerchView组件设置事件监听器
		svSearch.setOnQueryTextListener(this);
		lvlend = (ListView) view.findViewById(R.id.lv_lend);
		tvTotal = (TextView) view.findViewById(R.id.tv_total);
		lvlend.setAdapter(lendAdapter);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// TODO Auto-generated method stub
		context = getActivity();
		lendAdapter = new lendAdapter(context);
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case Constance.UPDATE_DATA:	//刷新数据
					getAllLendInfo();
					break;
				default:
					break;
				}
			}

		};
	}
	
	public static Handler getHandler() {
		return handler;
	}

	/**
	 * 用户单击搜索按钮时调用该方法
	 */
	@Override
	public boolean onQueryTextSubmit(String query) {
		getLendInfoByParam(query);
		lendAdapter.setData(lendList);
		lendAdapter.notifyDataSetChanged();
		if (lendList == null) {
			tvTotal.setText("共计 0  条数据");
		} else {
			tvTotal.setText("共计 " + lendList.size() + "  条数据");
		}
		
		return false;
	}

	/**
	 * 用户输入字符时调用该方法
	 */
	@Override
	public boolean onQueryTextChange(String newText) {
		// TODO Auto-generated method stub
		getLendInfoByParam(newText);
		lendAdapter.setData(lendList);
		lendAdapter.notifyDataSetChanged();
		if (lendList == null) {
			tvTotal.setText("共计 0  条数据");
		} else {
			tvTotal.setText("共计 " + lendList.size() + "  条数据");
		}
		return false;
	}

	/**
	 * 数据适配器类，给Listview填充数据
	 */
	public class lendAdapter extends BaseAdapter {
		private List<LendInfo> lendList; 
		private LayoutInflater myInflater; // LayoutInfalter对象用来导入布局

		public lendAdapter(Context context) {
			this.myInflater = LayoutInflater.from(context);
		}

		public void setData(List<LendInfo> lendList) {
			this.lendList = lendList;
		}

		public int getCount() {
			if (this.lendList != null) {
				return this.lendList.size();
			}
			return 0;
		}

		public Object getItem(int paramInt) {
			return this.lendList.get(paramInt);
		}

		public long getItemId(int paramInt) {
			return paramInt;
		}

		// 绘制ListItem的方法
		public View getView(final int position, View paramView,
				ViewGroup paramViewGroup) {
			View view = paramView;
			ViewHolder holder = null;

			if (paramView == null) {
				// 加载ListItem布局文件
				view = myInflater.inflate(R.layout.lend_item,
						null);
				holder = new ViewHolder();
				// 得到各个控件的对象
				holder.tvLendId = (TextView) view.findViewById(R.id.tv_lendid);
				holder.bnReLend = (Button) view.findViewById(R.id.bn_relend);
				holder.ivBook = (ImageView) view.findViewById(R.id.iv_book);
				holder.tvBookName = (TextView) view.findViewById(R.id.tv_bookname);
				holder.tvUserName = (TextView) view.findViewById(R.id.tv_username);
				holder.tvCardId = (TextView) view.findViewById(R.id.tv_cardid);
				holder.tvStarting = (TextView) view.findViewById(R.id.tv_starting);
				holder.tvExpiring = (TextView) view.findViewById(R.id.tv_expiring);
				// 绑定ViewHolder对象到view上
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag(); // 取出ViewHolder对象
			}
			// 得到当前ListItem需要填充的图书数据
			LendInfo lend = this.lendList.get(position);
			if (lend != null) {
				holder.tvLendId.setText(lend.getId() + "");
				holder.ivBook.setBackgroundResource(lend.getBookInfo().getImageId());
				holder.tvBookName.setText(lend.getBookInfo().getName());
				holder.tvUserName.setText(lend.getUsername());
				holder.tvCardId.setText(lend.getCardid());
				holder.tvStarting.setText(lend.getStarting());
				holder.tvExpiring.setText(lend.getExpiring());
			}
			holder.bnReLend.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					new AlertDialog.Builder(context)
                    .setTitle("温馨提示")
                    .setMessage("续借时间为1个月")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                        	LendInfo lendInfo = lendList.get(position);
                        	//续借
                        	boolean relendResult = LendService.relend(context, lendInfo);
                        	if (relendResult) {
                        		Toast.makeText(context, "续借成功！", 1).show();
                        		getAllLendInfo();
                        	}
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    }).show();
				}
			});
			
			// 把图书的数据设置到ListItem控件上
			return view;

		}

	}

	/**
	 * ListItem界面控件的持有类
	 */
	class ViewHolder {
		TextView tvLendId;
		Button bnReLend;
		ImageView ivBook;
		TextView tvBookName;
		TextView tvUserName;
		TextView tvCardId;
		TextView tvStarting;
		TextView tvExpiring;
	}
	
	
}
